<template>
	<view>
		<u-form :model="form" ref="uForm" id="form-container" @submit.prevent="submit">
			<u-form-item label="名称" prop="facilityName" :label-width="labelWidth" required>
				<u-input v-model="form.facilityName"  @blur="PlanNoblur"/>
			</u-form-item>
			<u-form-item label="编号" prop="facilityBarcode" :label-width="labelWidth" required>
				<u-input v-model="form.facilityBarcode" @blur="PlanNoblur"/>
			</u-form-item>
			<u-form-item label="型号" prop="facilityBarcodeType3" :label-width="labelWidth" required>
				<u-input v-model="form.facilityBarcodeType3"/>
			</u-form-item>
			<u-form-item label="大类" prop="facilityBarcodeType1" :label-width="labelWidth" required>
				   <u-input v-model="form.facilityBarcodeType1"/>
				<!-- <div class="u-flex u-flex-nowrap u-row-between">
				   <u-input v-model="form.facilityBarcodeType1" disabled/>
				   <u-button slot="right" type="success" :ripple="true" size="mini" @click="getBarcodeType('大类')" class="machineBtn">选择工作中心</u-button>
				   <u-picker mode="selector" v-model="DLshow" :range="barcodeType1List" @confirm="DXconfirm('大类')"></u-picker>
				</div> -->
			</u-form-item>
			<u-form-item label="小类" prop="facilityBarcodeType2" :label-width="labelWidth" required>
				<u-input v-model="form.facilityBarcodeType2"/>
			</u-form-item>
			<u-form-item label="部门" prop="workCenter" :label-width="labelWidth" required>
				<div class="u-flex u-flex-nowrap u-row-between">
				   <u-input v-model="form.workCenter" disabled/>
				   <u-button slot="right" type="success" :ripple="true" size="mini" @click="showworkCenter = true" class="machineBtn">选择部门</u-button>
				   <u-picker mode="selector" v-model="showworkCenter" :range="workCenterList" @confirm="workCenterconfirm"></u-picker>
				</div>
			</u-form-item>
			<u-form-item label="位置" prop="warehouseLocation" :label-width="labelWidth" required>
				<div class="u-flex u-flex-nowrap u-row-between">
				   <u-input v-model="form.warehouseLocation" disabled/>
				   <u-button slot="right" type="success" :ripple="true" size="mini" @click="showdevi = true" class="machineBtn">选择位置</u-button>
				   <u-picker mode="selector" v-model="showdevi" :range="placeList" @confirm="Bardcodesconfirm"></u-picker>
				</div>
			</u-form-item>
		点检项目：
		<u-table align="center">
				<u-tr>
					<u-th style="width:10rpx">序号</u-th>
					<u-th>{{name + '内容'}}</u-th>
					<u-th>合格</u-th>
					<u-th>涉及</u-th>
				</u-tr>
				<u-tr v-for="(item,index) in list" :key="index">
					<u-td >{{ index + 1 }}</u-td>
					<u-td align="center"><u-input v-model="item.content"/></u-td>
					<u-td align="center"><u-switch style="margin-left: 30rpx;" size="40" v-model="item.isAccomplish" ></u-switch></u-td>
					<u-td align="center"><u-switch style="margin-left: 30rpx;" size="40" v-model="item.isInvolve" ></u-switch></u-td>
				</u-tr>
			</u-table>
			<!-- <u-form-item :label="name+`时间`" prop="updateTime" :label-width="labelWidth" required>
				<div class="u-flex u-flex-nowrap u-row-between">
				   <u-input v-model="form.updateTime" disabled/>
				   <u-button slot="right" type="success" :ripple="true" size="mini" @click="timeShow = true" class="machineBtn">选择时间</u-button>
					<u-picker mode="time" v-model="timeShow" :params="params" @confirm="confirmtime"
					cancel="canceltime"></u-picker>
				</div>
			</u-form-item> -->
			<u-form-item :label="name+`人员`" prop="spotJobNumber" :label-width="labelWidth" required>
				<u-input v-model.trim="form.spotJobNumber"  @blur="changeJobNumber" :placeholder="`输入`+name+`人员工号`"/>
			</u-form-item>
		</u-form>
			<!-- <u-form-item v-if="radio == '输入姓名'" label="维修人员姓名" prop="feedbackName" :label-width="labelWidth" required>
				<u-input v-model="form.feedbackName" placeholder="输入人员姓名" @blur="changeName" :disabled="radio != '输入姓名'"/>
			</u-form-item> -->
			<div style="display: flex;">
			<view class="toTop">
				<u-upload
				@on-success="sucess"
				@on-remove="remove" 
				:max-count="1" 
				:width="300" 
				:height="200" 
				ref="uUpload"
				:action="action"
				:auto-upload="true" ></u-upload>
				请点击上传设备图片
			</view>	
			<u-image width="300px" height="200rpx" :src="form.img"></u-image>
			</div>
			<u-form-item class="u-flex u-row-center">
				<u-button type="success" size="medium" @click="submit">提交</u-button>
			</u-form-item>
			<u-top-tips ref="uTips"></u-top-tips>
	</view>
</template>

<script>
	import { saveFeedbackJobNumber,find_user,getPlanList,getPlanMachine,getWokeCenterList,maintenanceSel,selbarcodeType,maintenanceUpd } from '../utils/index.js'
	export default {
		data() {
			return {
				action: 'https://www.golwayhhln.top/hnsMes/fileTransmit/detectionFile',
				barcodeType1List: [],
				barcodeType2List: [],
				barcodeType3List: [],
				DLshow: false,
				QJshow: false,
				qjContent: '',
				radio: '输入工号',
				showworkCenter: false,
				workCenterList:[],
				 params: {
						year: true,
						month: true,
						day: true,
					    hour: true,
						minute: true,
						second: true
					},
				// 库房位置列表
				placeList: ['EMS工具房','EMS装备库','数控模具库','数控工装检具库','焊接工装检具库','喷涂工装检具库','装配工装库','装配检具库'],
				list:[],
				deviceBardcodeList:[],
				showworkCenter: false,
				showdeviceBardcodes:false,
				showdevi: false,
				labelWidth: 160,		//表单每一项的宽度
				autoHeight: true,		//表单“描述”输入框自动高度
				type: 'textarea',		//将描述的输入框设置为textarea
				rules: {						//表单提交前的验证
					deviceBarcode: [{
							required: true, 
							message: '请输入内容', 
							trigger: 'blur',
					}],
					feedbackJobNumber: [{
							required: true, 
							message: '维修人员工号不能为空！', 
							trigger: 'blur',
					}],
					feedbackName: [{
							required: true, 
							message: '维修人员名字不能为空！', 
							trigger: 'blur',
					}],
					feedbackOrderType: [{
							required: true, 
							message: '工单单别不能为空！', 
							trigger: 'blur',
					}],
					feedbackWorkOrderNo: [{
							required: true, 
							message: '工单单号不能为空！', 
							trigger: 'blur',
					}],
					// feedbackPlanNo: [{
					// 		required: true, 
					// 		message: '排产序号不能为空！', 
					// 		trigger: 'blur',
					// }],
					feedbackProcessOrder: [{
							required: true, 
							message: '对应工序不能为空！', 
							trigger: 'blur',
					}],
					processName: [{
							required: true, 
							message: '工序名称不能为空！', 
							trigger: 'blur',
					}],
				},
				form: {},
				user: uni.getStorageSync('user'),
				ecnImgUrl:'',
				timeShow: false,
				mode: 'range',
				name:'',
				rules: {						//表单提交前的验证
					facilityName: [{
							required: true, 
							message: '名称不能为空', 
							trigger: 'blur',
					}],
					facilityBarcode: [{
							required: true, 
							message: '编号不能为空！', 
							trigger: 'blur',
					}],
					facilityBarcodeType3: [{
							required: true, 
							message: '型号不能为空！', 
							trigger: 'blur',
					}],
					facilityBarcodeType1: [{
							required: true, 
							message: '大类不能为空！', 
							trigger: 'blur',
					}],
					facilityBarcodeType2: [{
							required: true, 
							message: '小类不能为空！', 
							trigger: 'blur',
					}],
					workCenter: [{
							required: true, 
							message: '部门不能为空！', 
							trigger: 'blur',
					}],
					warehouseLocation: [{
							required: true, 
							message: '位置不能为空！', 
							trigger: 'blur',
					}],
					updateTime: [{
							required: true, 
							message: '点检时间不能为空！', 
							trigger: 'blur',
					}],
					spotJobNumber: [{
							required: true, 
							message: '点检人员不能为空！', 
							trigger: 'blur',
					}],
				},
			}
		},
		async onLoad(options) {
			let info = JSON.parse(JSON.stringify(options))
			if(info.name == '设备点检'){
			   this.name = '点检'
			} else {
			   this.name = '保养'
			}
			uni.setNavigationBarTitle({
				title: '设置'+this.name
			});
			let query = {
				type: info.type, 
				facilityBarcode: info.facilityBarcode, 
				facilityBarcodeType1: info.facilityBarcodeType1, 
				facilityBarcodeType2: info.facilityBarcodeType2,
				facilityName: info.facilityName,
				facilityBarcodeType3: info.facilityBarcodeType3, 
				timeId: info.timeId
			}
			query.page = 1
			query.limit = 10000
			const res = await maintenanceSel(query)
			if(res.data.data.list.length){
				this.list = res.data.data.list
				this.list.forEach(item => {
					item.isAccomplish == 1 ? item.isAccomplish = false :item.isAccomplish = true
					item.isInvolve == 1 ? item.isInvolve = false : item.isInvolve = true
				})
				console.log('11',this.list);
				this.form = res.data.data.list[0]
			}
			const {data} = await getWokeCenterList()
			this.workCenterList = data.data
			this.form.workCenter = uni.getStorageSync('user').departmentName
		},
		methods:{
			confirmtime(e){
            //此处实现选择器值的接收
			this.form.updateTime = e.year +'-'+ e.month + '-'+
             e.day+' '+ e.hour + ':'+ e.minute+ ':'+ e.second
		    },
			sucess(e){
				console.log('拍照上传',e)
				this.ecnImgUrl = e.data.results
				// this.form.img = e.data.results
				this.$refs.uTips.show({
					title: '上传成功！',
					type: 'success',
					duration: '2000'
				})
			},
			remove(index){
				console.log(index)
				this.ecnImgUrl = ''
			},
			// 工作中心先择
			workCenterconfirm(e){
				this.form.workCenter = this.workCenterList[e[0]]
			},
			// 位置
			Bardcodesconfirm(e){
				this.form.warehouseLocation = this.placeList[e[0]]
			},
			async getBarcodeType(type) {
			            let query = {
			                facilityBarcodeType: type,
			                page: 1,
			                limit: 10000
			            }
			            let data = await selbarcodeType(query)
			            let errmsg = data.msg
			            if(data.code == '500') return
			            if(data.code != '1') return this.$message.error(errmsg)
			            if(type == '大类'){
			                this.barcodeType1List = data.data.records
			            } else if(type == '小类') {
			                this.barcodeType2List = data.data.records
			            } else if(type == '规格') {
			                this.barcodeType3List = data.data.records
			            }
			            this.DLshow = true
			        },
			async PlanNoblur(){
				console.log(123);
				if(this.form.feedbackOrderType && this.form.feedbackWorkOrderNo){
					let query = {}
				     query = {
				    	orderType: this.form.feedbackOrderType,
				    	workOrderNo: this.form.feedbackWorkOrderNo,
				    	page: 1,
				    	limit: 1000
				    }
				    const {data} = await getPlanMachine(query)
				    console.log(data.data.List);
					if(!data.data.List.length){
						this.form.feedbackProcessOrder = ''
						this.form.processName = ''
					}
					this.deviceBardcodeList = data.data.List
				}
			},
			// 点击按钮，启用扫码
		    scanFun() {
		    	let that = this
		    	uni.scanCode({
		    		onlyFromCamera: true,
		    		success: function (res) {
						// if(res.result.includes('06S')){that.form.deviceBarcode = res.result.match(/06S(\S*)1P/)[1]}
		    			that.form.deviceBarcode = res.result
		    		},
		    		fail() {
		    			console.log('识别失败')
		    		}
		    	})
		    },
			// 表单验证
			submit() {
				this.$refs.uForm.validate(valid => {
					if (valid) {
						console.log('验证通过')
						this.postForm()
					} else {
						this.$refs.uTips.show({
							title: '请完善表单数据!',
							type: 'warning',
							duration: '2000'
						})
					}
				})
			},
			// 提交整个表单，提交按钮绑定的函数
			async postForm(val) {	
				for (const item of this.list) {
				    // 执行操作
					if(!item.content) return  this.$refs.uTips.show({
					title: `请填写内容！`,
					type: 'warning',
					duration: '2000'
				})
				}
				if(!this.ecnImgUrl) return this.$refs.uTips.show({
					title: '请上传图片！',
					type: 'warning',
					duration: '2000'
				})
				// let query = Object.assign({},this.form)
				// console.log(this.list);
				//   if(this.list.length ){
				// 	  let arr = JSON.parse(JSON.stringify(this.list))
				//       arr.forEach(item => {
				// 	  item.isAccomplish = item.isAccomplish ? 0 : 1
				// 	  item.isInvolve = item.isInvolve ? 0 : 1
				//   })
				  // query.code = arr.map(obj => obj['code']).join(',');
				  // query.emsFacilityMaintenanceItemConfigurationId = arr.map(obj => obj['id']).join(',');
				  // query.content = arr.map(obj => obj['content']).join(',');
				  // query.isAccomplish = arr.map(obj => obj['isAccomplish']).join(',');
				  // query.isInvolve = arr.map(obj => obj['isInvolve']).join(',');
				// }
				this.list.forEach(async item => {
					// let query = JSON.parse(JSON.stringify(this.form))
					// query.isAccomplish = item.isAccomplish ? 0 : 1
					// query.isInvolve = item.isInvolve ? 0 : 1
					// query.emsFacilityMaintenanceItemConfigurationId = item.id
					let query = {
						isAccomplish: item.isAccomplish ? 0 : 1,
						isInvolve: item.isInvolve ? 0 : 1,	
						img: this.ecnImgUrl,
						id: item.id
					}
					console.log('query',query);
					let keyStr = '';
					let times = 1;
					// 传路劲参数
					for(let key in query) {
						if(times === 1) {
							keyStr += `?${key}=${query[key]}`;
							console.log(key);
						} else {
							keyStr += `&${key}=${query[key]}`;
						}
						times++;
					}
					console.log(11,keyStr);
				   let { data } = await maintenanceUpd(keyStr)
				    if(data.code == '1') {
				    	this.$refs.uTips.show({
				    		title: '提交成功！',
				    		type: 'success',
				    		duration: '2000'
				    	})
						setTimeout(()=>
						   {
						     uni.redirectTo({
						     	url: '../../login/login'
						     })
						   }, 2000)
				    } else {
				    	this.$refs.uTips.show({
				    		title: data.msg,
				    		type: 'error',
				    		duration: '2000'
				    	})
				    }	
				})
			},
			async changeName(val) {
				if(!val) return
				let query = {
					userName: this.form.feedbackName
				}
				let { data } = await find_user(query)
				if(data.data) {
					this.$set(this.form,'feedbackJobNumber',data.data.jobNumber)
					// this.form.feedbackJobNumber = data.data.jobNumber
					this.$refs.uTips.show({
						title: `查询成功！姓名：${data.data.userName},  工号：${data.data.jobNumber}`,
						type: 'success',
						duration: '2000'
					})
				} else {
					this.$set(this.form,'feedbackName','')
					this.$set(this.form,'feedbackJobNumber','')
					this.$refs.uTips.show({
						title: '查询失败',
						type: 'error',
						duration: '2000'
					})
				}
			},
			async changeJobNumber(val) {
				if(!val) return
				let query = {
					jobNumber: this.form.spotJobNumber
				}
				let { data } = await find_user(query)
				if(data.data) {
					this.$set(this.form,'spotJobNumber',data.data.jobNumber)
					// this.form.jobNumber = data.data.userName
					this.$refs.uTips.show({
						title: `查询成功！姓名：${data.data.userName},  工号：${data.data.jobNumber}`,
						type: 'success',
						duration: '2000'
					})
				} else {
					this.$set(this.form,'spotJobNumber','')
					this.$refs.uTips.show({
						title: '查询失败',
						type: 'error',
						duration: '2000'
					})
				}
			},
			async searchFeedbackPlanNo(){
				if(!this.form.feedbackOrderType) return this.$refs.uTips.show({
					title: '工单单别不能为空!',
					type: 'error',
					duration: '2000'
				})
				if(!this.form.feedbackWorkOrderNo) return this.$refs.uTips.show({
					title: '工单单号不能为空!',
					type: 'error',
					duration: '2000'
				})
				let query = {
					orderType: this.form.feedbackOrderType,
					workOrderNo: this.form.feedbackWorkOrderNo,
				}
				let {data} = await getPlanList(query)
				console.log('排产编号')
				if(data.code == '1') {
					this.form.feedbackPlanNo = data.data.records[0].planNo
				} else {
					this.$refs.uTips.show({
						title: data.msg,
						type: 'error',
						duration: '2000'
					})
				}
			}
		},
		
		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		}
	}
</script>

<style>
	.main-content {
		width: 100%;
	}
	#form-container ::v-deep .u-form-item {
		margin-top: 15rpx;
		padding: 10rpx 30rpx;
	}
	.content {
		padding: 24rpx;
		text-align: center;
	}
	.buttonGap {
		margin-top: 20rpx;
	}
	.page-font {
		font-size: 30rpx;
		margin-top: 20rpx
	}
	.page-font text{
		text-align: center;
	}
	.sureBtn{
		margin-top: 20rpx;
		width: 90%;
	}
	.toTop{
		margin-top: 20rpx;
		/* background-color: #c4d79b; */
	}
</style>
